ProductsManagePortlet = Class.extend({
	init: function()	{
		this.name = "ProductsManagePortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		this.loadProducts();
	},
	
	loadProducts: function()	{
		var obj = this;
		this.onAjax('product', 'browse-products', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.model = {};
				for(var i=0;i<ret.length;i++)	{
					if (ret[i].is_featured == 1)
						ret[i].is_featured = "checked='checked'";
					else
						ret[i].is_featured = "";
					
					if (ret[i].is_new == 1)
						ret[i].is_new = "checked='checked'";
					else
						ret[i].is_new = "";
				}
				obj.model.products = ret;
				obj.model.root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
				obj.getPortletPlaceholder().paintCanvas(obj.render());
				obj.loadCategories();
			}
		});
	},
	
	onProductsChanged: function()	{
		this.run();
	},
	
	loadCategories: function()	{
		this.onAjax('categories', 'load-leaf-categories', {}, 'GET', {
			'onSuccess': function(ret)	{
				$('.categories-select').each(function() {
					var id = $(this).attr('cid');
					var pid = $(this).attr('pid');
					var select = $('<select onchange="generateEvent(&apos;ProductCategoryChanged&apos;, {id: '+pid+', event: event})"></select>');
					for(var i=0;i<ret.length;i++)	{
						var option = '<option value="'+ret[i].id+'">'+ret[i].name+'</option>';
						$(select).append($(option));
					}
					$(select).val(id);
					$(this).html(select);
				});
			}
		});
	},
	
	onProductCategoryChanged: function(eventData)	{
		var event = eventData.event.target;
		var id = eventData.id;
		this.onAjax('admin', 'update-product', {id: id, category_id: $(event).val()}, 'POST', {});
	},
	
	onProductNewStatusChanged: function(eventData)	{
		var event = eventData.event;
		var id = eventData.id;
		var checked = ($(event.target).is(':checked'));
		if (checked == true) checked = 1
		else checked = 0;
		this.onAjax('admin', 'update-product', {id: id, is_new: checked}, 'POST', {});
	},
	
	onProductFeaturedStatusChanged: function(eventData)	{
		var event = eventData.event;
		var id = eventData.id;
		var checked = ($(event.target).is(':checked'));
		if (checked == true) checked = 1
		else checked = 0;
		this.onAjax('admin', 'update-product', {id: id, is_featured: checked}, 'POST', {});
	},
	
	onDeleteProduct: function(eventData)	{
		var event = eventData.event;
		var id = eventData.id;
		var obj = this;
		this.onAjax('admin', 'delete-product', {id: id}, 'POST', {
			'onSuccess': function(ret)	{
				obj.run();
			}
		});
	},
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);